﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TvViewer.MpTvService;
using System.IO;
using System.Reflection;

namespace TvViewer
{
  public partial class OptionsForm : Form
  {
    public OptionsForm()
    {
      InitializeComponent();
    }

    private void OptionsForm_Load(object sender, EventArgs e)
    {
      Properties.Settings.Default.Reload();
      String url = Properties.Settings.Default.TvViewer_MpTvService_ServiceInterface;
      String defaultGroup = Properties.Settings.Default.DefaultGroup;
      bool showAllGroup = Properties.Settings.Default.ShowAllGroup;
      String deinterlaceMode = Properties.Settings.Default.DeinterlaceMode;
      int rtspBuffering = Properties.Settings.Default.RtspBuffering;
      bool autoStart = Properties.Settings.Default.TvAutoStart;
      int defaultVolume = Properties.Settings.Default.DefaultVolume;
      bool useInternal = Properties.Settings.Default.UseInternalVlc;
      String externalVlcPath = Properties.Settings.Default.ExternalVlcPath;


      txtDefaultGroup.Text = defaultGroup;
      cbShowAllChannels.Checked = showAllGroup;
      foreach (String s in cbDeinterlaceModes.Items)
      {
        if (s.Equals(deinterlaceMode))
        {
          cbDeinterlaceModes.SelectedItem = s;
          break;
        }
      }
      txtRtspBuffering.Text = rtspBuffering.ToString();

      cbUserInternalVlc.Checked = useInternal;
      txtExternalVlcPath.Text = externalVlcPath;
      txtExternalVlcPath.Enabled = !useInternal;
      cmdBrowseVlcPath.Enabled = !useInternal;

      tbDefaultVolume.Value = defaultVolume;
      cbAutoStart.Checked = autoStart;

      try
      {
        url = url.Replace("http://", "");
        url = url.Replace("/TvServiceWebServices.asmx", "");

        string[] urlport = url.Split(':');

        txtServerUri.Text = urlport[0];
        txtServerPort.Text = urlport[1];
      }
      catch (Exception ex)
      {

      }
      //server = new ServiceInterface();
      //server.Url = "http://bagga-server:8080/TvServiceWebServices.asmx";
      //SupportedMPFunctions f = server.GetSupportedMPFunctions();

    }

    private void cmdTest_Click(object sender, EventArgs e)
    {
      try
      {
        ServiceInterface server = new ServiceInterface();
        server.Url = Util.CreateWebServiceUrl(txtServerUri.Text, txtServerPort.Text);
        SupportedMPFunctions f = server.GetSupportedMPFunctions();

        txtServerResponse.BackColor = Color.Green;
        txtServerResponse.Text = "Successfully connected to server";

        WebChannelGroup[] groups = server.GetTvChannelGroups();
        cbAvailableGroups.Items.Clear();
        foreach (WebChannelGroup g in groups)
        {
          cbAvailableGroups.Items.Add(g.name);
        }
        cbAvailableGroups.Enabled = true;
      }
      catch (Exception ex)
      {
        txtServerResponse.BackColor = Color.OrangeRed;
        txtServerResponse.Text = "Error connecting to server";
        cbAvailableGroups.Items.Clear();
        cbAvailableGroups.Enabled = false;
      }
    }



    private void cbAvailableGroups_SelectedIndexChanged(object sender, EventArgs e)
    {
      txtDefaultGroup.Text = (String)cbAvailableGroups.SelectedItem;
    }

    private void cmdSave_Click(object sender, EventArgs e)
    {
      Properties.Settings.Default.TvViewer_MpTvService_ServiceInterface = Util.CreateWebServiceUrl(txtServerUri.Text, txtServerPort.Text);
      Properties.Settings.Default.DefaultGroup = txtDefaultGroup.Text;
      Properties.Settings.Default.ShowAllGroup = cbShowAllChannels.Checked;
      Properties.Settings.Default.ExternalVlcPath = txtExternalVlcPath.Text;
      Properties.Settings.Default.UseInternalVlc = cbUserInternalVlc.Checked;
      Properties.Settings.Default.TvAutoStart = cbAutoStart.Checked;
      Properties.Settings.Default.DefaultVolume = tbDefaultVolume.Value;

      if (txtRtspBuffering.Text.Equals(""))
      {
        Properties.Settings.Default.RtspBuffering = 0;
      }
      else
      {
        int rtspBufferMs;
        if (Int32.TryParse(txtRtspBuffering.Text, out rtspBufferMs))
        {
          Properties.Settings.Default.RtspBuffering = rtspBufferMs;
        }
      }
      
      Properties.Settings.Default.DeinterlaceMode = (String)cbDeinterlaceModes.SelectedItem;
      Properties.Settings.Default.FirstTime = false;
      Properties.Settings.Default.Save();
      this.DialogResult = DialogResult.OK;
    }

    private void cmdCancel_Click(object sender, EventArgs e)
    {
      this.DialogResult = DialogResult.Cancel;
    }

    private void cmdBrowseVlcPath_Click(object sender, EventArgs e)
    {
      FolderBrowserDialog diag = new FolderBrowserDialog();
      if (diag.ShowDialog(this) == DialogResult.OK)
      {
        if (CheckVlcPath(diag.SelectedPath))
        {
          txtExternalVlcPath.Text = diag.SelectedPath;
        }
        else
        {
          MessageBox.Show("Couldn't find vlc in the selected directory");
        }
      }

    }

    private bool CheckVlcPath(string _path)
    {
      {
        if (File.Exists(Path.Combine(_path, "libvlc.dll")) &&
            File.Exists(Path.Combine(_path, "libvlccore.dll")) &&
            Directory.Exists(Path.Combine(_path, "plugins")))
        {
          return true;
        }
        else
        {
          return false;
        }
      }
    }

    private void cbUserInternalVlc_CheckedChanged(object sender, EventArgs e)
    {
      if (cbUserInternalVlc.Checked)
      {
        if (!CheckVlcPath(Path.Combine(GetStartupPath(), "libvlc")))
        {
          MessageBox.Show("Can't find internal player, are you sure you installed the full version?");
          cbUserInternalVlc.Checked = false;
          return;
        }
      }
      txtExternalVlcPath.Enabled = !cbUserInternalVlc.Checked;
      cmdBrowseVlcPath.Enabled = !cbUserInternalVlc.Checked;
    }

    private static string GetStartupPath()
    {
      return Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
    }
  }
}
